package com.heima.gateway.app.fileter;

import com.heima.gateway.app.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 过滤器
 *
 * @author 11494
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/2/29 20:30:46
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter {
    /**
     * 功能描述：网关统一token鉴权
     *
     * @param exchange
     * @param chain
     * @return {@link Mono }<{@link Void }>
     * @author sungang
     * @date 2024/02/29  20:34
     */

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("----------------进入网关--------------");
        try {
            ServerHttpResponse response = exchange.getResponse();
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            //如果是登录直接放行
            if (path.contains("login")) {
                return chain.filter(exchange);
            }
            //如果不是登录
            String token = request.getHeaders().get("token").get(0);
            if (token == null) {
                response.setStatusCode(HttpStatus.HTTP_VERSION_NOT_SUPPORTED);
                return response.setComplete();
            }
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i == -1 || i == 0) {
                return chain.filter(exchange);
            } else {
                response.setStatusCode(HttpStatus.HTTP_VERSION_NOT_SUPPORTED);
                return response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }
}
